package com.example.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.Service.XsCustomertService;
import com.example.exception.MyException;

import com.example.pojo.XsCustomer;
import com.example.util.Result;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
@CrossOrigin
@RequestMapping("/xscustomert")
@Api(tags = "销售客户信息")
public class XsCustomertController {

    @Resource
    private XsCustomertService xsCustomertService;


    //获取销售客户信息列表
    @GetMapping("/getlist")
    public Object getList(
            @RequestParam(value = "customerId",defaultValue = "") Integer customerId,
            @RequestParam(value = "customerName",defaultValue = "") String customerName,
            @RequestParam(value = "PageNum",defaultValue = "") int PageNum,
            @RequestParam(value = "PageSize",defaultValue = "") int PageSize
    ){
        HashMap<String,Object> map=new HashMap<>();
        QueryWrapper<XsCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(customerId!=null,"customer_id",customerId);
        queryWrapper.like(customerName!=null,"customer_name",customerName);
        Page<XsCustomer> page = new Page<>(PageNum,PageSize);
        Page<XsCustomer> xScustomerPage = xsCustomertService.page(page, queryWrapper);
        map.put("total",xScustomerPage.getTotal());
        map.put("rows",xScustomerPage.getRecords());
        map.put("pages",xScustomerPage.getPages());
        return new Result<>("200","查询成功",map);
    }
    //添加客户信息

    @SuppressWarnings("rawtypes")
    @PostMapping("/add")
    public Result add(@RequestBody XsCustomer xScustomer){
        QueryWrapper<XsCustomer> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id",xScustomer.getCustomerId());
        int count = (int) xsCustomertService.count(wrapper);
        if (count>0){
        throw new MyException("457","客户信息已存在");
        }
        if (!xsCustomertService.save(xScustomer)){
            throw new MyException("458","添加客户信息失败");
        }

        return new Result<>("200","添加客户信息成功");
    }

//   修改客户信息
    @PutMapping("/update")
    public Result update(@RequestBody XsCustomer xScustomer){
        if (!xsCustomertService.updateById(xScustomer)){
         throw new MyException("459","修改客户信息失败");
        }
        return new Result<>("200","修改客户信息成功");
    }

//   删除客户信息
    @DeleteMapping("/delete")
    public Result delete(@RequestParam("customerId") Integer customerId){
        if (!xsCustomertService.removeById(customerId)){
            throw new MyException("460","删除客户信息失败");
        }
        return new Result<>("200","删除客户信息成功");
    }






}
